import rrwebPlayer from 'rrweb-player'
import pako from 'pako'
import React, { useRef, useState } from 'react'
import 'rrweb-player/dist/style.css'
import './App.css'
const rrweb = require('rrweb')

function App() {
	
  const [isPlaying, setIsPlaying] = useState(false)
  const videoRef = useRef()

  let replay = null
  let events = []
	let textValue = ''
	let stopFn = null
	
	/**
	 * 录制数据压缩
	 * @param {Object} str
	 * @return {String} base64
	 */ 
	const zip = (str) => {
		let binaryString = pako.gzip(encodeURIComponent(str), { to: 'string' })
		return btoa(binaryString)
	}
	/**
	 * 解压录制数据（采用分段解压的方式，防止解压数据限制出现内存溢出）
	 * @param {Object} b64Data
	 */
	const unzip = (b64Data) => {
		let strData = atob(b64Data)
		// 使用charCodeAt把每个Unicode编码存放到Unit8Array 中
		let charData = strData.split('').map(item => item.charCodeAt(0))
		let binData = new Uint8Array(charData)
		let data = pako.inflate(binData)
		let arr = new Uint16Array(data)
		let res = ''
		let i
		let chunk = 8 * 1024
		for (i = 0; i < arr.length / chunk; i++) {
			res += String.fromCharCode.apply(null, arr.slice(i * chunk, (i + 1) * chunk))
		}
		res += String.fromCharCode.apply(null, arr.slice(i * chunk)) // ArrayBuffer转String
		strData = res
		return decodeURIComponent(strData) // 对字符串数据进行解码
	}
	
	/**
	 * 开始记录（为防止一次性提交数据量过大，可定时更新）
	 */
  const startFn = () => {
    stopFn = rrweb.record({
      emit(event) {
        // 将 event 存入 events 数组中
        events.push(event)
      },
    })
  }
	
	/**
	 * 完成录制
	 */
	const completeFn = () => {
		// 上传数据到服务端
	}
	
	/**
	 * 回放
	 */
  const replayFn = () => {
    stopFn()
    setIsPlaying(true)
    setTimeout(() => {
      if (videoRef.current) {
        if (replay) return
        replay = new rrwebPlayer({
          target: videoRef.current, 
          // 配置项
          props: {
            events,
						// events: this.unzip(JSON.stringify(res.data)) // 从服务端获取数据，对数据进行解压
          },
        })
      }
    }, 1)
  }
	const changeFn = (e) => {
		console.log('3e====', e)
	}

  return (
    <div className="App">
      <div className="btn-wrap">
        <button onClick={() => startFn()}>开始录制</button>
        <button onClick={() => replayFn()}>回放</button>
        <button onClick={() => completeFn()}>完成</button>
      </div>
      <div className="textArea-wrap">
        <textarea rows="10" cols="50" placeholder="在此输入信息">
				</textarea>
      </div>
      {isPlaying ? 
        <div id="replay" ref={videoRef} /> 
        : null}
    </div>
  )
}

export default App
